import store from '@/store'

const state = {
    tabs: [],
    currTabs: {},
    tabViews: []
}
const mutations = {
    toggle: (state, to) => {
        if (to && to.path && to.path.includes('/login')) return;
        var curr = state.tabs.find(t => t.path == to.path)
        if (!curr) {
            state.tabs.push(to)
            state.currTabs = to

        } else {
            state.tabs.forEach(t => {
                if (t.path == to.path) {
                    t = curr
                    state.currTabs = curr

                }
            })
        }
    },
    remove: (state, tab) => {
        state.tabs = state.tabs.filter(t => t.path != tab.path)
    },
    changeName: (state, { name, path }) => {
        state.tabs = state.tabs.map((t, i) => {
            if (t.path == path) {
                t.meta.name = name
            }
            return t;
        })
    }
}
const actions = {
    to: ({ commit }, to) => {
        commit('toggle', to)
    },
    close: async ({ commit }, tab) => {
        commit('remove', tab)
        var s = store
        // var res = await s._modules.root.state.route.keepAliveViews[0]()
    },
    changeName: ({ commit }, params) => {
        commit('changeName', params)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}